<style scoped>
	.file {
		position: relative;
		display: inline-block;
		background: #20a0ff;
		border: 1px solid #20a0ff;
		border-radius: 4px;
		padding: 6.5px 15px;
		overflow: hidden;
		color: #fff;
		text-decoration: none;
		text-indent: 0;
		line-height: 20px;
		top: 12px;
	}
	.file input {
		position: absolute;
		font-size: 120px;
		cursor: pointer;
		right: 0;
		top: 0;
		opacity: 0;
	}
	.file:hover {
		background: #4db3ff;
		border-color: #4db3ff;
		color: #fff;
		text-decoration: none;
	}
</style>
<template>
	<div>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters" ref="filters" :rules="rule">
				<el-form-item prop="date">
					<el-date-picker
						v-model="filters.date"
						range-separator="至"
						type="datetimerange"
						placeholder="选择时间范围">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="open('EXPLAIN')">提现说明</el-button>
					<el-button type="primary" @click="open('SET')">提现设置</el-button>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="filters.status" clearable>
						<el-option v-for="item,index in statusList" :label="item.name" :value="item.id" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="搜索条件" prop="trade">
					<el-select v-model="filters.trade" clearable>
						<el-option label="用户ID" value="1"></el-option>
						<el-option label="用户昵称" value="2"></el-option>
						<el-option label="提现单号" value="3"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="" prop="input" v-if="!filters.trade == ''">
					<el-input v-if="filters.trade == '1'" v-model="filters.input" placeholder="用户ID"></el-input>
					<el-input v-if="filters.trade == '2'" v-model="filters.input" placeholder="用户姓名"></el-input>
					<el-input v-if="filters.trade == '3'" v-model="filters.input" placeholder="提现单号"></el-input>
				</el-form-item>
				<el-form-item style="display: block">
					<el-button type="primary" @click="getList">查找</el-button>
					<a href="javascript:;" class="file">导入表格
						<input id="upload" type="file" @change="importfxx(this)"  accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
					</a>
					<el-button type="primary" @click="outExe">导出表格</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<el-col>
			<el-table :data="dataList">
				<div v-for="item,index in columns">
					<el-table-column v-if="item.prop" :label="item.title" :align="item.align" :min-width='item.width' :prop="item.prop" :key="index">
					</el-table-column>
					<el-table-column v-if="item.prop == undefined" :label="item.title" :align="item.align" :min-width='item.width' :key="index">
						<template slot-scope="scope">
							<el-tag type="primary" v-if="scope.row[item.s] == 1">进行中</el-tag>
							<el-tag type="success" v-if="scope.row[item.s] == 2">成功</el-tag>
							<el-tag type="danger" v-if="scope.row[item.s] == 3">失败</el-tag>
						</template>
					</el-table-column>
				</div>
			</el-table>
			<!--工具条-->
			<div class="toolbar" style="display: flex;justify-content: flex-end;">
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="size"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total">
				</el-pagination>
			</div>
		</el-col>
		<el-dialog :title="this.type == 1 ? '提现设置' : this.type == 2 ? '提现说明' : ''" :visible.sync="dialogWithdrawSet" size="tiny">
			<div v-if="this.type == 1">
				<el-form :model="setForm" ref="setForm" :rules="setFormRule">
					<el-form-item label="最低提现金额/次" label-width="140px" prop="lowMoney">
						<el-input placeholder="输入正整数" v-model="setForm.lowMoney">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
					<el-form-item label="提现次数上限/日" label-width="140px" prop="lowCount">
						<el-input placeholder="输入正整数" v-model="setForm.lowCount">
							<template slot="append">次</template>
						</el-input>
					</el-form-item>
				</el-form>
			</div>
			<div v-if="this.type == 2">
				<el-input
					type="textarea"
					:autosize="{ minRows: 2, maxRows: 4}"
					placeholder="请输入内容"
					v-model="content">
				</el-input>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogWithdrawSet = false">取 消</el-button>
				<el-button type="primary" @click="setSubmit('setForm')">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import { getWithdrawList, setWithdraw, withImport, withContent } from '@/api/api'
	export default {
		data() {
			let validateInput = (rule, value, callback) => {
				if (!value) {
					callback(new Error('不能为空'));
				} else {
					callback();
				}
			};
			let validateNumber = (rule, value, callback) => {
				if (!value) {
					callback(new Error('不能为空'));
				} else if(!Number.isInteger(Number(value))) {
					callback(new Error('输入正整数'));
				} else {
					callback();
				}
			};
			return {
				da: [],
				type: 0,// 弹框判断
				filters: {
					date: '',
					status: '',
					trade: '',
					input: ''
				},
				start: '',
				end: '',
				statusList: [
					{id: "1", name: '进行中'},
					{id: "2", name: '成功'},
					{id: "3", name: '失败'}
				],
				rule: {
					input: [
						{validator: validateInput, trigger: 'blur' }
					]
				},
				dataList: [],
				total: 0,
				size: 10,
				currentPage: 1,
				columns: [
					{},
					{title: '提现单号',align: 'center',width: '140',prop: 'withNum'},
					{title: '用户ID',align: 'center',width: '140',prop: 'userId'},
					{title: '用户姓名',align: 'center',width: '140',prop: 'name'},
					{title: '提现金额',align: 'center',width: '140',prop: 'amount'},
					{title: '状态',align: 'center',width: '140',s: 'status'},
					{title: '累计提现进行中金额',align: 'center',width: '140',prop: 'amountIn'},
					{title: '累计提现成功金额',align: 'center',width: '140',prop: 'amountSuccess'},
					{title: '提现时间',align: 'center',width: '140',prop: 'createTime'},
				],
				// 提现设置&&说明弹出框
				dialogWithdrawSet: false,
				setForm: {
					lowMoney: '',
					lowCount: ''
				},
				setFormRule: {
					lowMoney: [
						{validator: validateNumber, trigger: 'blur' }
					],
					lowCount: [
						{validator: validateNumber, trigger: 'blur' }
					],
				},
				content: ''
				
			};
		},
		methods: {
			getTime() {
				let starttime,endtime = ''
				let time = this.filters.date;
				if(!time[0] == '') {
					starttime = this.moment(time[0]).format();
				}
				if(!time[1] == '') {
					endtime = this.moment(time[1]).format();
				}
				if(starttime == "Invalid date"){
					starttime="";
				};
				if(endtime == "Invalid date"){
					endtime="";
				};
				this.start = starttime
				this.end = endtime
			},
			getList() {
				this.getTime();
				let para = {
					pageIndex: this.currentPage,
					pageSize: this.size,
				};
				if(!this.start == '') {
					para.startTime = this.start
				}
				if(!this.end == '') {
					para.endTime = this.end
				}
				if(!this.filters.status == "") {
					para.status = this.filters.status
				}
				if(!this.filters.trade == '') {
					if(this.filters.trade == 1) {
						para.userId = this.filters.input.replace(/\s/g, "")
					}
					if(this.filters.trade == 2) {
						para.name = this.filters.input.replace(/\s/g, "")
					}
					if(this.filters.trade == 3) {
						para.withNum = this.filters.input.replace(/\s/g, "")
					}
				}
				getWithdrawList(para).then(res => {
					this.filters.input = ''
					this.dataList = res.data.data;
					this.dataList.map(v => {
						v.createTime = this.moment(v.createTime).format('YYYY-MM-DD HH:mm:ss')
					})
					this.total = res.data.totalCount;
				})
			},
			open(type) {
				if(type == 'SET') {
					this.type = 1
					withContent({}).then(res => {
						this.setForm.lowMoney = res.data.minAmount
						this.setForm.lowCount = res.data.maxCount
					})
				}
				if(type == 'EXPLAIN') {
					this.type = 2
					withContent({}).then(res => {
						this.content = res.data.withContent
					})
				}
				this.dialogWithdrawSet = true
			},
			setSubmit(setForm) {
				if(this.type == 1) {
					this.$refs[setForm].validate((valid) => {
						if(valid) {
							let para = {
								minAmount: this.setForm.lowMoney,
								maxCount: this.setForm.lowCount
							}
							setWithdraw(para).then(res => {
								this.$message({
									message: '设置成功',
									type: 'success'
								});
								this.$refs[setForm].resetFields();
								this.dialogWithdrawSet = false
							})
						}
					})
				}
				if(this.type == 2) {
					let para = {
						withContent: this.content
					}
					setWithdraw(para).then(res => {
						this.$message({
							message: '设置成功',
							type: 'success'
						});
						this.dialogWithdrawSet = false
					})
				}
			},
			// 分页详情
			handleSizeChange(val) {
				this.size = val;
				this.getList();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getList();
			},
			// 导入
			importfxx(obj) {
				let _this = this;
				let inputDOM = this.$refs.inputer;
				// 通过DOM取文件数据
				this.file = event.currentTarget.files[0];
				var rABS = false; //是否将文件读取为二进制字符串
				var f = this.file;
				var reader = new FileReader();
				//if (!FileReader.prototype.readAsBinaryString) {
				FileReader.prototype.readAsBinaryString = function(f) {
					var binary = "";
					var rABS = false; //是否将文件读取为二进制字符串
					var pt = this;
					var wb; //读取完成的数据
					var outdata;
					var reader = new FileReader();
					reader.onload = function(e) {
						var bytes = new Uint8Array(reader.result);
						var length = bytes.byteLength;
						for(var i = 0; i < length; i++) {
							binary += String.fromCharCode(bytes[i]);
						}
						var XLSX = require('xlsx');
						if(rABS) {
							wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
								type: 'base64'
							});
						} else {
							wb = XLSX.read(binary, {
								type: 'binary'
							});
						}
						outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
						this.da = [...outdata]
						let arr = []
						this.da.map(v => {
							let obj = {}
							obj.id = v.id
							obj.status = v.status
							arr.push(obj)
						})
						console.log(arr)
						let para = {
							//withList: JSON.stringify(this.da)
							withList: arr
						}
						_this.$message({
							message: '请耐心等待导入成功',
							type: 'success'
						});
						withImport(para).then(res => {
							window.location.reload()
						})
						
					}
					reader.readAsArrayBuffer(f);
				}
				if(rABS) {
					reader.readAsArrayBuffer(f);
				} else {
					reader.readAsBinaryString(f);
				}
			},
			// 导出
			outExe() {
				this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.excelData = this.dataList
					this.export2Excel()
				}).catch(() => {
				
				});
			},
			export2Excel() {
				var that = this;
				require.ensure([], () => {
					const { export_json_to_excel } = require('../../excel/Export2Excel');
					const tHeader = ['id','withNum', 'userId', 'name','amount','status','amountIn','amountSuccess','createTime'];
					const filterVal = ['id','withNum','userId', 'name','amount','status','amountIn','amountSuccess','createTime'];
					const list = that.excelData;
					const data = that.formatJson(filterVal, list);
					let time1,time2 = '';
					if(this.start !== '') {
						time1 = that.moment(that.start).format('YYYY-MM-DD')
					}
					if(this.end !== '') {
						time2 = that.moment(that.end).format('YYYY-MM-DD')
					}
					export_json_to_excel(tHeader, data, `[${time1}-${time2}]提现管理excel`);
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
		},
		mounted() {
			this.getList();
		}
	}
</script>
